package com.szqhyxj.youxiangju;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by leung on 2018/11/16.
 */
public abstract class LazyFragment extends Fragment {

    protected View parentView;
    protected boolean visible;
    protected boolean viewInit;
    protected boolean dateInit;
    Unbinder unbinder;

    protected abstract void start();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        parentView = inflater.inflate(getLayoutId(), null, false);
        unbinder = ButterKnife.bind(this, parentView);
        viewInit = true;
        checkAndStart();
        return parentView;
    }

    @Override
    public void onResume(){
        super.onResume();

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        visible = isVisibleToUser;
        checkAndStart();
    }

    private void checkAndStart() {
        String name = getClass().getName();
        if (dateInit) {
            return;
        }
        if (viewInit && visible) {
            start();
            dateInit = true;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    /**
     * @return 布局 id
     */
    protected abstract int getLayoutId();

}